<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!-- 为了一对一聊天，我们这里需要获取到用户名-->
<input type="text" id="username"><button onclick="login()">登录聊天室</button>
给<input type="text" id="to_user">发:<input type="text" id="msg"><button onclick="send_msg()">发送</button>
<div id="chat_list" style="width: 500px;height: 500px;"></div>
</body>
<script type="application/javascript">
    <!--python script是异步代码-->
    var ws = null;

    function login() {
        var username = document.getElementById("username").value;
        ws = new WebSocket("ws://127.0.0.1:9527/ws/"+username);
        ws.onmessage = function (data) {
        console.log(data.data);
        var recv_msg = JSON.parse(data.data);
        var ptag = document.createElement("p");
        ptag.innerText = recv_msg.from_user + ": " + recv_msg.msg;
        document.getElementById("chat_list").appendChild(ptag);
    };
    }

    function send_msg() {
        //这里是是input标签所以这里使用value
        var to_user = document.getElementById("to_user").value;
        var msg = document.getElementById('msg').value;
        var send_str = {
            "to_user":to_user,
            "msg":msg
        };
        ws.send(JSON.stringify(send_str))


    }
</script>

</html>